﻿using AutoMapper;
using B.S.ProcessEngine.ErrorCode;
using B.S.SmartStorPro.Domain;
using B.S.SmartStorPro.Infrastructure;
using B.S.SmartStorPro.Infrastructure.Interfaces;
using B.S.SmartStorPro.Read.API.DTO;
using MediatR;
using Microsoft.OpenApi.Extensions;
using System.DirectoryServices.Protocols;
using System.Text;

namespace B.S.SmartStorPro.Read.API.AppLication.Login
{
    // 登录命令处理程序类
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<UserDTO>>
    {
        private readonly IBaseRepository<Users> userRepository;
        private readonly IMapper mapper;

        public LoginCommandHandler(IBaseRepository<Users> userRepository, IMapper mapper)
        {
            this.userRepository = userRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<UserDTO>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserDTO> result = new APIResult<UserDTO>();
            result.Code = EventHandle.ErrorCode.APIEnums.登录成功;
            result.Message = EventHandle.ErrorCode.APIEnums.登录成功.ToString();

            #region 登录
            var allUsers = await userRepository.GetAllAsync();
            var entity = allUsers.FirstOrDefault(x => x.UserName == request.UserName);
            if (entity == null)
            {
                result.Code = EventHandle.ErrorCode.APIEnums.登录失败;
                result.Message = EventHandle.ErrorCode.APIEnums.登录失败.ToString() + "," + "用户名不存在";
            }
            else if (entity.UserPwd != request.UserPwd)
            {
                result.Code = EventHandle.ErrorCode.APIEnums.登录失败;
                result.Message = EventHandle.ErrorCode.APIEnums.登录失败.ToString() + "," + "用户名密码不匹配";
            }
            var login = mapper.Map<UserDTO>(entity);
            result.Data = login;
            #endregion

            return result;
        }
    }
}
